<template>
  <div class="car-comparison">
    <div class="top-header">
      <div class="title-container">
        <button class="back-btn" @click="goBack">返回</button>
        <h1>智能比价</h1>
      </div>
    </div>

    <!-- 添加按钮 -->
    <div class="add-car-section">
      <button class="add-car-btn" @click="showCarSelector" v-if="selectedCars.length < 5">
        <span class="plus">+</span>
        <span>添加产品</span>
      </button>
    </div>

    <!-- 车型选择弹窗 -->
    <div class="car-selector" v-if="selectorVisible">
      <div class="selector-mask" @click="hideCarSelector"></div>
      <div class="selector-content">
        <div class="selector-header">
          <h3>选择产品</h3>
          <button class="close-btn" @click="hideCarSelector">×</button>
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
          <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索型号..."
              @input="filterCars"
          >
        </div>

        <div class="car-list" ref="carList">
          <div
              v-for="car in filteredCars"
              :key="car.id"
              class="car-item"
          >
            <img :src="car.image" :alt="car.name" />
            <div class="car-brief">
              <p class="name">{{ car.name }}</p>
              <p class="price">￥{{ car.price }}元起</p>
            </div>
            <!-- 配置版本选择 -->
            <div class="trim-list">
              <div
                  v-for="trim in getAvailableTrims(car)"
                  :key="trim.id"
                  class="trim-item"
                  :class="{'trim-selected': isTrimSelected(car, trim)}"
                  @click="selectCarWithTrim(car, trim)"
              >
                <span class="trim-name">{{ trim.name }}</span>
                <span class="trim-price">￥{{ trim.price }}元</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 对比详情区 -->
    <div class="comparison-details" v-if="selectedCars.length > 0">
      <div class="comparison-scroll" :class="{'scrollable': selectedCars.length > 1}">
        <div class="comparison-table">
          <!-- 表头 -->
          <div class="detail-row header">
            <div class="detail-col label">型号</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              <div class="car-header-content">
                <img :src="car.image" :alt="car.name" />
                <p class="car-name">{{ car.name }}</p>
                <p class="trim-name">{{ car.selectedTrim.name }}</p>
                <button class="remove-btn" @click="removeCar(car)">×</button>
              </div>
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 价格 -->
          <div class="detail-row">
            <div class="detail-col label">售价</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              <span class="price">￥{{ car.selectedTrim.price }}元</span>
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 配置版本 -->
          <div class="detail-row">
            <div class="detail-col label">配置型号</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              {{ car.selectedTrim.name }}
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 发动机 -->
          <div class="detail-row">
            <div class="detail-col label">基础算力</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              {{ car.engine }}
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 变速箱 -->
          <div class="detail-row">
            <div class="detail-col label">供电电压</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              {{ car.transmission }}
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 油耗 -->
          <div class="detail-row">
            <div class="detail-col label">运动速度</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              {{ car.fuelConsumption }}
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 尺寸 -->
          <div class="detail-row">
            <div class="detail-col label">站立尺寸</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              {{ car.size }}
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>

          <!-- 配置 -->
          <div class="detail-row features">
            <div class="detail-col label">主要配置</div>
            <div class="detail-col" v-for="car in selectedCars" :key="car.id">
              <ul>
                <li v-for="(feature, index) in car.selectedTrim.features" :key="index">
                  {{ feature }}
                </li>
              </ul>
            </div>
            <div class="detail-col empty" v-for="n in (5 - selectedCars.length)" :key="n"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'

// 已选择的车辆
const selectedCars = ref([])

// 选择器显示状态
const selectorVisible = ref(false)

// 搜索关键词
const searchQuery = ref('')

// 可选择的车辆列表
const availableCars = reactive([
  {
    id: 1,
    name: 'Unitree Go2',
    price: '9997',
    image: '/src/assets/img/phone/AIR.png',
    engine: '铝合金',
    transmission: '28V~33.6V',
    fuelConsumption: '0~2.5m/s',
    size: '70x31x40cm',
    trims: [
      {
        id: 1,
        name: 'AIR',
        price: '9997',
        features: ['智能电池', '高清广角相机', '探物避障', '图形化编程']
      },
      {
        id: 2,
        name: 'PRO',
        price: '18600',
        features: ['智能电池', '高清广角相机', '探物避障', '图形化编程','语音功能', 'ISS 2.0智能避障','8核高性能CPU']
      },
    ]
  },
  {
    id: 2,
    name: '通用人形',
    price: '100,000',
    image: '/src/assets/img/phone/H1.png',
    engine: '铝合金',
    transmission: '最大电压67.2V',
    fuelConsumption: '移动速度3.3m/s(世界纪录)',
    size: '(1520+285)*570*220mm',
    trims: [
      {
        id: 1,
        name: 'H1',
        price: '100,000',
        features: ['5（髋关节 × 3 + 膝关节 × 1 + 踝关节 × 1）', '工业级交叉滚子轴承（高精度，高承载力']
      },
      {
        id: 2,
        name: 'H1-2',
        price: '200,000',
        features: ['6 (髋关节 × 3 + 膝关节 × 1 + 踝关节 × 2)', '工业级交叉滚子轴承（高精度，高承载力']
      }
    ]
  },
  // 可以添加更多车型...
])

watch(selectedCars, (newValue) => {
  if (newValue.length >= 2) {
    hideCarSelector()
  }
}, { deep: true })

// 过滤后的车辆列表
const filteredCars = computed(() => {
  return availableCars
      .filter(car => hasAvailableTrims(car))
      .filter(car =>
          car.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          car.price.includes(searchQuery.value)
      )
})

// 检查车型是否还有可选配置
const hasAvailableTrims = (car) => {
  return car.trims.some(trim => !isTrimSelected(car, trim))
}

// 获取车型可选配置
const getAvailableTrims = (car) => {
  return car.trims.filter(trim => !isTrimSelected(car, trim))
}

// 检查配置是否已被选择
const isTrimSelected = (car, trim) => {
  return selectedCars.value.some(selected =>
      selected.id === car.id && selected.selectedTrim.id === trim.id
  )
}

// 返回上一页
const goBack = () => {
  history.back()
}

// 显示车型选择器
const showCarSelector = () => {
  selectorVisible.value = true
  searchQuery.value = '' // 重置搜索
}

// 隐藏车型选择器
const hideCarSelector = () => {
  selectorVisible.value = false
  searchQuery.value = '' // 重置搜索
}

// 选择车型和配置版本
const selectCarWithTrim = (car, trim) => {
  if (selectedCars.value.length < 5 && !isTrimSelected(car, trim)) {
    const selectedCar = {
      ...car,
      selectedTrim: trim
    }
    selectedCars.value.push(selectedCar)
    if (!hasAvailableTrims(car)) {
      hideCarSelector()
    }
  }
}

// 移除对比车型
const removeCar = (car) => {
  const index = selectedCars.value.findIndex(selected =>
      selected.id === car.id && selected.selectedTrim.id === car.selectedTrim.id
  )
  if (index !== -1) {
    selectedCars.value.splice(index, 1)
  }
}
</script>

<style scoped>
.car-comparison {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.top-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #000;
  padding: 10px 15px;
  z-index: 100;
}

.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-container h1 {
  color: #fff;
  font-size: 18px;
  margin: auto;
  margin-right: 130px;
}

.back-btn {
  padding: 4px 5px;
  background: transparent;
  color: white;
  border: 1px solid white;
  border-radius: 4px;
  font-size: 12px;
}

.add-car-section {
  margin-top: 50px;
  padding: 15px;
}

.add-car-btn {
  width: 100%;
  padding: 15px;
  background: white;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 16px;
}

.add-car-btn .plus {
  font-size: 24px;
  margin-right: 8px;
}

.car-selector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.selector-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
}

.selector-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-radius: 16px 16px 0 0;
  padding: 20px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 15px;
}

.search-box input {
  width: 95%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
}

.search-box input:focus {
  border-color: #409eff;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.selector-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
}

.car-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  overflow-y: auto;
  padding: 5px;
  -webkit-overflow-scrolling: touch;
}

.car-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 8px;
  background: white;
  transition: all 0.3s;
}

.car-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.car-item img {
  width: 100%;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.car-brief {
  margin-top: 8px;
}

.car-brief .name {
  font-size: 14px;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.car-brief .price {
  color: #f56c6c;
  font-size: 12px;
  margin: 4px 0 0;
}

/* 配置版本列表样式 */
.trim-list {
  margin-top: 10px;
  border-top: 1px solid #eee;
  padding-top: 8px;
}

.trim-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.trim-item:hover {
  background: #f5f5f5;
}

.trim-item.trim-selected {
  background: #f0f0f0;
  border-color: #ddd;
  cursor: not-allowed;
  opacity: 0.5;
}

.trim-name {
  font-size: 12px;
  color: #333;
}

.trim-price {
  font-size: 12px;
  color: #f56c6c;
}

.comparison-details {
  flex: 1;
  overflow: hidden;
  margin-top: 10px;
}

.comparison-scroll {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 10px;
}

.comparison-scroll.scrollable {
  overflow-x: auto;
}

.comparison-table {
  min-width: 100%;
  background: white;
}

.detail-row {
  display: flex;
  border-bottom: 1px solid #eee;
  background: white;
}

.detail-row.header {
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}

.detail-col {
  flex: 1;
  min-width: 100px;
  max-width: 100px;
  padding: 10px;
  font-size: 11px;
  text-align: center;
  background: white;
}

.detail-col.empty {
  background: #f9f9f9;
}

.detail-col.label {
  flex: 0 0 100px;
  min-width: 100px;
  max-width: 100px;
  background: #f8f8f8;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  position: sticky;
  left: 0;
  z-index: 2;
}

.car-header-content {
  position: relative;
  padding: 5px;
}

.car-header-content img {
  width: 140px;
  height: 90px;
  object-fit: cover;
  border-radius: 4px;
}

.car-name {
  margin: 8px 0 4px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.trim-name {
  margin: 0 0 8px;
  font-size: 12px;
  color: #666;
}

.remove-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: none;
  background: rgba(0,0,0,0.5);
  color: white;
  font-size: 16px;
  line-height: 1;
  padding: 0;
  cursor: pointer;
}

.features ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left;
}

.features li {
  margin: 5px 0;
  font-size: 12px;
}
</style>
